﻿/*
2019-4-19 创建

一些知识，关于request.ContentType

常用格式如下：
    text/html ： HTML格式
    text/plain ：纯文本格式      
    text/xml ：  XML格式
    image/gif ：gif图片格式    
    image/jpeg ：jpg图片格式 
    image/png：png图片格式

以application开头的媒体格式类型：
   application/xhtml+xml ：XHTML格式
   application/xml     ： XML数据格式
   application/atom+xml  ：Atom XML聚合格式    
   application/json    ： JSON数据格式
   application/pdf       ：pdf格式  
   application/msword  ： Word文档格式
   application/octet-stream ： 二进制流数据（如常见的文件下载）
   application/x-www-form-urlencoded ： <form encType=””>中默认的encType，form表单数据被编码为key/value格式发送到服务器（表单默认的提交数据的格式）

 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WindGoes6.Web
{
    public class WebApiInvoker
    {

        public static string GetHttpRequest(string url)
        {
            string html = null;
            try
            {
                WebClient webClient = new WebClient();
                // webClient.Credentials = CredentialCache.DefaultCredentials; 
                byte[] pageData = webClient.DownloadData(url);
                //string pageHtml = Encoding.Default.GetString(pageData);        
                html = Encoding.UTF8.GetString(pageData);
            }
            catch (WebException webEx)
            {
                Console.WriteLine(webEx.Message);
            }
            return html;
        }


        /// <summary>
        /// 调用指定的url以post方式调用，默认超时时间为3000毫秒。
        /// </summary>
        /// <param name="url">待调用链接。</param>
        /// <param name="param">参数列表，格式如 api=value1&arg1=value2</param>
        /// <param name="timeout">超时时间（单位毫秒），默认值为3000。</param>
        /// <returns>执行结果。</returns>
        public static string InvokeWebApiPost(string url, string param, int timeout = 3000)
        {
            // 将参数字节化
            byte[] postdatabyte = Encoding.UTF8.GetBytes(param);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.Timeout = timeout;
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            // request.ContentLength = postdatabyte.Length;
            request.AllowAutoRedirect = false;
            request.KeepAlive = false             ;
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            try
            { 
                using (Stream stream = request.GetRequestStream())
                    stream.Write(postdatabyte, 0, postdatabyte.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // 获取返回值。
            string returned = null;
            try
            {
                Stream responseStream = request.GetResponse().GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                returned = streamReader.ReadToEnd();
                responseStream.Close();
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            return returned;
        }
    }
}
